var util = require('../../utils/util.js')
const app = getApp()

Page({
    /**
     * 初始化页面数据
     */
    data:{
        currentYear:'',
        offSetDay:'',
        isLeapYear:false,
        allDays:'',
        isAuth:false,
        showPopup: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        BackgroundMeImg:'',
        auth_me_id:[],
    },
    //获取全局设置信息
    getAllSetting(){
        var p= new Promise((resolve,reject)=>{
            var requestUrl=app.globalData.apiBase+ "/blog/getAllSetting";
            util.ajax(requestUrl,'get',null,(res)=>{
                let authMeId = res.auth_me_id;
                this.setData({
                    auth_me_id:authMeId.split(","),
                    BackgroundMeImg:res.blog_background_me_picturl
                })

                var serverUserId=(this.data.auth_me_id+'').replace(/^\s+|\s+$/g,"")
                var localUserId=(app.globalData.userId+'').replace(/^\s+|\s+$/g,"")
                resolve(res);
            })
        })
        return p
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options){
        let isAuth = this.userAuthoriaztion();
        if(isAuth){
            this.setData({
                avatarUrl:app.globalData.userInfo.avatarUrl,
                nickName:app.globalData.userInfo.nickName
            })
            this.computedYear()
        }
    },
    toRemind(){
        wx.navigateTo({
            url:'/pages/plain/plain-add/plain-add?title='+"日程提醒"
        })
    },
    /**
     * 查看授权状态
     */
    userAuthoriaztion() {
        // 1.查看授权状态
        if (app.globalData.userInfo != null) { //如果是分享过来的页面，用户手机里面的userinfo肯定为空
            this.setData({
                showPopup: false
            })
            return true
        }else{
            this.setData({
                showPopup: true
            })
            return false
        }
    },
    //开始授权
     doNext(){
         wx.showLoading({
             title: '正在授权中'
         });
        console.log(this.data.showPopup + "--------授权状态")
        if (this.data.showPopup) {
            console.log("开始调用登录")
            this.checkLogin()
                .then(this.trueLogin)
                .then(()=>{
                    this.setData({
                        showPopup:false,
                        avatarUrl:app.globalData.userInfo.avatarUrl,
                        nickName:app.globalData.userInfo.nickName
                    })
                    this.computedYear()
                })

        }
    },
    /**
     * 授权登录(为了当用户从分享页进来，没有授权信息，导致后台接口调用发生权限不足的情况)
     */
    checkLogin() {
        var p = new Promise(function (resolve, reject) {
            wx.getSetting({    //获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限 返回值：请求过的权限可以通过res.authSetting拿到
                success: (res) => {
                    if (res.authSetting['scope.userInfo']) { //用户是否授权通过(弹出框用户点击了确定)res.authSetting[scope.userInfo]可以判断
                        wx.getUserInfo({
                            success: (res) => {
                                app.globalData.userInfo = res.userInfo;
                                resolve(res);
                            },
                            fail: (error) => {
                                console.log('系统错误')
                            }
                        })
                    }
                },
                fail: (error) => {
                    console.log('获取用户信息失败');
                    reject(error)
                }
            })
        })
        return p
    },
    /**
     * 真正调用后台登录接口
     * @returns {Promise<any>}
     */
    trueLogin() {
        var p = new Promise(function (resolve, reject) {
            let that = this;
            //调用接口获取登录凭证（code）
            wx.login({
                success: (res) => {
                    wx.request({
                        url: app.globalData.apiBase + '/blog/loginSubmit',
                        data: {
                            code: res.code,
                            nickname: app.globalData.userInfo.nickName,
                            avatar: app.globalData.userInfo.avatarUrl
                        },
                        method: 'POST',
                        header: {
                            'content-type': 'application/json',
                            'clientType': 'WX',
                            'appId': 'wx56561420351f2442'
                        },
                        success: (res) => {
                            if (res.data.respCode === '0000') {
                                app.globalData.userId = res.data.respResult.userId;
                                app.globalData.token = res.data.respResult.token;
                                resolve(res)
                            } else {
                                wx.showToast({
                                    title: '登录gg了，快联系作者吧',
                                    icon: 'none',
                                    duration: 1500
                                })
                            }
                            wx.hideLoading();
                        },
                        fail: (error) => {
                            reject(error)
                        }
                    })
                },
                fail: (error) => {
                    console.log('获取用户信息失败');
                    reject(error)
                }
            })
        })
        return p
    },
    onTabChange(event) {
        let turnFlag=event.detail
        var url=''
        console.log(turnFlag)
        switch(turnFlag)
        {
            case 0:
                url='/pages/posts/post'
                break;
            case 1:
                url='/pages/special/special'
                break;
            case 2:
                url='/pages/security/security'
                break;
            case 3:
                url='/pages/me/me'
                break;
            default:
                url=''
        }
        //这里是一个坑：微信自从改版之后redirectTo和navigateTo均不可以跳转有tabbar的页面了
        //这里又一个关于navigator的bug:https://www.jb51.net/article/131543.htm
        //为了防止重定向的时候出现闪屏效果，先让当前页面出栈，然后在重定向
        getCurrentPages().pop()
        wx.redirectTo({
            url: url
        })

    },
    /**
     * 时间计算
     */
    computedYear(){
        //获取年份
        this.setData({
            currentYear:new Date().getFullYear()
        })
        //获取天数
        let start=new Date()
        start.setMonth(0)
        start.setDate(1)
        //    start就是今年的第一天
        //    现在的时间戳-今年第一天的时间戳(单位毫秒)
        let offSet=new Date().getTime()- start.getTime()
        this.setData({
            offSetDay:parseInt(offSet/1000/60/60/24)+1
        })
        let isleapYear = this.isLeapYear();
        this.setData({
            allDays:isleapYear?366:365
        });
        this.getPercent()
    },
    getPercent(){
        let that=this
        this.setData({
            percentDegree:parseFloat((parseFloat(that.data.offSetDay)*100/that.data.allDays)).toFixed(1)
        })
    },
    //是否是闰年
    isLeapYear(){
        const year= new Date().getFullYear()
        if(year%400===0){
            return true
        }else if(year%4===0&&year%100!==0){
            return true
        }else{
            return false
        }
    },
    /**
     * 回到首页(分享的时候)
     */
    navigateBack: function () {
        wx.switchTab({
            url: '/pages/posts/post'
        })
    },
    onShow(){
        this.getAllSetting()
    }
})
